package com.zhangxujie.litewords.ui.querywords;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.JsonReader;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.zhangxujie.litewords.R;
import com.zhangxujie.litewords.api.Const;
import com.zhangxujie.litewords.dao.WordsDAO;
import com.zhangxujie.litewords.db.AppDatabase;
import com.zhangxujie.litewords.db.DBUtil;
import com.zhangxujie.litewords.entity.Words;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;

public class QueryWordsFragment extends Fragment {


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        final View root = inflater.inflate(R.layout.fragment_querywords, container, false);

        final TextView textView = root.findViewById(R.id.editText_queryword);
        final ImageView btn = root.findViewById(R.id.imageButton);
        final WebView webViewQuery = root.findViewById(R.id.webview_query);
        final ImageView imageView = root.findViewById(R.id.word_query_img);

        @SuppressLint("HandlerLeak") final Handler queryHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                Words w = (Words) msg.obj;
                webViewQuery.setWebViewClient(new WebViewClient() {
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        return true;
                    }
                });

                if (w.id < 0) {

                    switch (w.id) {
                        case -1:
                            Toast.makeText(root.getContext(), "查询数据不能为空！", Toast.LENGTH_SHORT).show();
                            webViewQuery.loadData("查询数据不能为空", "text/html", "UTF-8");
                            break;
                        case -2:
                            Toast.makeText(root.getContext(), "未查询到该单词信息！", Toast.LENGTH_SHORT).show();
                            webViewQuery.loadData("未查询到该单词信息，请检查拼写正确性！", "text/html", "UTF-8");
                            break;
                        case -3:
                            Toast.makeText(root.getContext(), "互联网连接失败！", Toast.LENGTH_SHORT).show();
                            webViewQuery.loadData("互联网连接失败！", "text/html", "UTF-8");
                            break;
                        default:
                    }
                    if (w.id == -2) {


                    } else if (w.id == -1) {
                    }
                } else if (w.id == 0) {
                    Toast.makeText(root.getContext(), "正在联网查询...", Toast.LENGTH_SHORT).show();
                    if (w.explaination.indexOf("常用英语教材") != -1) {
                        webViewQuery.loadData("无该单词数据，请检查拼写正确性！", "text/html", "UTF-8");
                    } else {
                        Glide.with(getContext()).load(w.imgUrl).into(imageView);
                        webViewQuery.loadData(w.explaination, "text/html", "UTF-8");
                    }
                } else {
                    if (w.explaination.indexOf("常用英语教材") != -1) {
                        webViewQuery.loadData("无该单词数据，请检查拼写正确性！", "text/html", "UTF-8");
                    } else {
                        webViewQuery.loadData(w.explaination, "text/html", "UTF-8");
                        Glide.with(getContext()).load(w.imgUrl).into(imageView);
                    }
                }

            }

        };

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppDatabase db = DBUtil.getDb(getContext());
                final WordsDAO dao = db.wordsDao();


                //本地查询单词
                new Thread() {
                    @Override
                    public void run() {
                        String wordText = textView.getText().toString();
                        Words w = new Words();
                        if (wordText.equals("")) {
                            w.id = -1;
                        } else {
                            w = dao.queryByWord(wordText);//本地查询
                            if (w == null) {
                                //联网查询
                                w = queryFromInternet(wordText, dao);
                            }
                        }
                        Message msg = new Message();
                        if (w == null) {
                            w = new Words();
                            w.id = -2;
                        }
                        msg.obj = w;
                        queryHandler.sendMessage(msg);
                    }
                }.start();

            }
        });


        return root;
    }

    public Words queryFromInternet(String wordText, WordsDAO dao) {
        Words w = new Words();
        String url = String.format(Const.QUERY_WORD_URL_Youdao, wordText);
        String imgAPI = String.format(Const.QUERY_PIC_URL_Youdao, wordText);
        Document contentDoc = null;//翻译
        Document imgJsonDoc = null;//图片url json

        Elements contentElem = null;
        String imgUrl = "";

        try {
            contentDoc = Jsoup.connect(url)
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                    .header("Accept-Encoding", "gzip, deflate")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                    .header("Content-Type", "text/html;charset=UTF-8")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36")
                    .ignoreContentType(true)
                    .timeout(10000).get();
            imgJsonDoc = Jsoup
                    .connect(imgAPI)
                    .header("Accept", "*/*")
                    .header("Accept-Encoding", "gzip, deflate")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
                    .ignoreContentType(true)
                    .timeout(10000).get();

            if (contentDoc != null) {
                contentElem = contentDoc.select("#phrsListTab > div.trans-container > ul");
            }

            w = new Words();
            w.word = wordText;
            w.version = 0;
            w.updateTime = System.currentTimeMillis();
            w.explaination = contentElem == null ? "" : contentElem.html();

            if (imgJsonDoc != null) {
                JSONObject jsonObj;
                try {
                    jsonObj = new JSONObject(imgJsonDoc.body().text());
                    imgUrl = jsonObj.getJSONObject("data").getJSONArray("pic").getJSONObject(0).getString("image");
                    Log.d("imgurl", "run: " + imgUrl);

                    w.imgUrl = imgUrl;

                } catch (JSONException e) {
                    e.printStackTrace();
                    w.imgUrl = "";
                }

            }

            if (!w.explaination.equals("")) {
                //查询到单词
                dao.insertAll(w);
                w.id = 0;
            }else {
                //未查询到单词！
                w = new Words();
                w.id = -2;
            }
        } catch (UnknownHostException ex) {
            w = new Words();
            w.id = -3;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return w;
    }


}
